#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "cube_component.h"

#include "dslinfo_report.h"

// add para lib_include
int dslinfo_report_init(void * sub_proc, void * para)
{
	int ret;
	// Init Tcm Func
//	ret=TCM_LibInit();

	// add yorself's module init func here
	return 0;
}
int dslinfo_report_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	sleep(1);

	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
		if((type==TYPE(GENERAL_RETURN))&&(subtype==SUBTYPE(GENERAL_RETURN,STRING)))
		{
			ret=proc_check_input(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_check_input(void * sub_proc,void * recv_msg)
{
	int ret=0;

	RECORD(GENERAL_RETURN,STRING)  *string_input;
	// get the query info
	ret =message_get_record(recv_msg,&string_input,0);
	if(ret<0)
		return -EINVAL;
    if(string_input==NULL)
        return -EINVAL;

	// build output message
	if(Strcmp(string_input->name,"ENUM")==0)
    {
        if(Strcmp(string_input->return_value,"elem_basetype")==0)
            proc_send_elem_basetype(sub_proc,recv_msg);	
    }

}

int proc_send_elem_basetype(void * sub_proc,void * recv_msg)
{
	int ret=0;
	int fd;

	BYTE Buf[DIGEST_SIZE*16];
	BYTE NameBuf[DIGEST_SIZE*4];
	UINT32 result;
	DB_RECORD * db_record;
	RECORD(CUBE_DESC,STRING_DESC)  *elem_basetype_desc;
	void * new_msg;

	// build output message
	new_msg=message_create(TYPE_PAIR(CUBE_DESC,STRING_DESC),recv_msg);	
	if(new_msg==NULL)
		return -EINVAL;
	
	elem_basetype_desc=memdb_get_first_record(TYPE_PAIR(CUBE_DESC,STRING_DESC));
	while(elem_basetype_desc!=NULL)
	{

        if(Strcmp(elem_basetype_desc->desc_set,"elem_basetype")==0)
        {
		    ret=message_add_record(new_msg,elem_basetype_desc);
			if(ret<0)
				return ret;
			ret=ex_module_sendmsg(sub_proc,new_msg);
	        new_msg=message_create(TYPE_PAIR(CUBE_DESC,STRING_DESC),recv_msg);	
			if(new_msg==NULL)
				return -EINVAL;
		}
	    elem_basetype_desc=memdb_get_next_record(TYPE_PAIR(CUBE_DESC,STRING_DESC));
	}		
	
	return ret;
}
